package util;

import java.lang.Thread.UncaughtExceptionHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	private static BasicDataSource ds;

	// /枚举
	public static enum ConnType {
		JDBC_ORACLE, // JDBC方式连接Oracle
		JNDI_ORACLE// /JNDI方式连接Oracle
	}

	// 单例，静态代码块只在类加载时执行
	static {
		ds = new BasicDataSource();
		ds.setUrl(Constants.ORACLE_URL);
		ds.setDriverClassName(Constants.ORACLE_CLASSNAME);
		ds.setUsername(Constants.ORACLE_USER);
		ds.setPassword(Constants.ORACLE_PSD);
	}

	// --------------------------------------------------------------------------------------
	// 公开方法
	// --------------------------------------------------------------------------------------

	public static Connection createConnection(ConnType connType) throws Exception{

		switch (connType) {
		case JDBC_ORACLE:
			return createConnectionA_JDBC_Oracle();
		case JNDI_ORACLE:
			return createConnection_JNDI_Oracle();
		default:
			return createConnection_JNDI_Oracle();
		}
	}

	public static void close(Connection con, PreparedStatement pst, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (pst != null)
				pst.close();
			if (con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// --------------------------------------------------------------------------------------
	// 私有实现
	// --------------------------------------------------------------------------------------

	private static Connection createConnectionA_JDBC_Oracle() throws SQLException {
		Connection con = null;
			con = ds.getConnection();
			return con;
		
	}

	private static Connection createConnection_JNDI_Oracle() throws Exception {
		
			// JNDI 树
			InitialContext cxt = new InitialContext();
			// 查看Web服务器 JDNI配置
			DataSource ds = (DataSource) cxt
					.lookup(Constants.ORACLE_JDNI_PATH);
			
			Connection conn = ds.getConnection();
			return conn;
	}

}
